//
//  LKLockScanViewController.m
//  LKIntelligentVideoProject
//
//  Created by she1323 on 2018/9/20.
//  Copyright © 2018年 she1323. All rights reserved.
//

#import "LKLockScanViewController.h"
#import "LKUserInforTool.h"
#import "LKBaseView.h"
#import <LBXAlertAction.h>
#import <Masonry.h>
#import "UIButton+Extension.h"
#import <LBXZBarWrapper.h>
#import "LKBillDetailViewController.h"
#import "LKTicketOperateViewController.h"
#import "LKCodeCashierViewController.h"
#import "LKTaiQianScanBindController.h"
@interface LKLockScanViewController ()


@end

@implementation LKLockScanViewController



-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self drawTitleItems];
    if (self.scanType == LKScanTypeCashier) {
        [self drawBottomItemsWithTitle:@"将顾客付款二维码放入框内，即可自动扫码"];
    }else if(self.scanType == LKScanTypeScan){
        [self drawBottomItemsWithTitle:@"请将条形码或二维码放入框内"];
        self.btnFlash.hidden = YES;
        self.headerLabel.hidden = YES;
        [self setNavgationRightBtnWithTile:@"相册"];
    }else if(self.scanType == LKScanTypeScanTicket){
        [self drawBottomItemsWithTitle:@"请将条形码或二维码放入框内"];
        self.btnFlash.hidden = YES;
        self.headerLabel.hidden = YES;
        [self setNavgationRightBtnWithTile:@"手动输入"];
    }else if (self.scanType == LKScanTypeHardware){
        [self drawBottomItemsWithTitle:@"扫描硬件设备上的二维码"];
        self.btnFlash.hidden = YES;
        self.headerLabel.hidden = YES;
    }else if (self.scanType == LKScanTypeScanTaiqian){
        [self drawBottomItemsWithTitle:@"扫描硬件设备上的二维码"];
        self.btnFlash.hidden = YES;
        self.headerLabel.hidden = YES;
    }

}
-(void)setNavgationRightBtnWithTile:(NSString *)title{
    WS(weakSelf)
    if (self.scanType == LKScanTypeScanTicket) {
           LKBaseButton *rightBtn = [LKBaseButton buttonWithFrame:CGRectMake(0, 0, 64, 24) type:UIButtonTypeCustom title:title titleColor:COLOR_HEX(0x333333) layercorne:13 font:[UIFont fontWithName:@"PingFangSC-Regular" size: 16] backgroudColor:[UIColor clearColor] AndActionBlock:^(UIButton * _Nonnull btn) {
               LKTicketOperateViewController *vc = [[LKTicketOperateViewController alloc] init];
               [weakSelf.navigationController pushViewController:vc animated:YES];
           }];
            self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    }else if (self.scanType == LKScanTypeScan){
           LKBaseButton *rightBtn = [LKBaseButton buttonWithFrame:CGRectMake(0, 0, 64, 24) type:UIButtonTypeCustom title:title titleColor:COLOR_HEX(0x333333) layercorne:13 font:[UIFont fontWithName:@"PingFangSC-Regular" size: 16] backgroudColor:[UIColor clearColor] AndActionBlock:^(UIButton * _Nonnull btn) {
        
           }];
            self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    }


}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.tabBarController.tabBar.hidden = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    if (self.scanType == LKScanTypeCashier) {
        self.navigationItem.title = @"扫一扫收款";
    }else if(self.scanType == LKScanTypeScan){
        self.navigationItem.title = @"扫一扫";
    }else if(self.scanType == LKScanTypeScanTicket){
        self.navigationItem.title = @"卡券扫码";
    }else if (self.scanType == LKScanTypeHardware){
        self.navigationItem.title = @"硬件扫描";
    }else if (self.scanType == LKScanTypeScanTaiqian){
        self.navigationItem.title = @"台签绑定";
    }
//    self.cameraInvokeMsg = @"相机启动中";
    [self setNavgationBackBtn];
}
-(void)createTopLabel{
    LKBaseLabel *headerLabel = [LKBaseLabel labelWithFrame:CGRectZero text:@"￥0.5" textColor:[UIColor whiteColor] font:[UIFont fontWithName:@"PingFangSC-Medium" size:36] textAlignment:NSTextAlignmentCenter];
    [self.view addSubview:headerLabel];
    [self.view bringSubviewToFront:headerLabel];
    [headerLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.view.mas_top).offset(20);
    }];
}
/**
 设置返回按钮样式
 */
-(void)setNavgationBackBtn{
    UIButton *button = [[UIButton alloc] init];
    [button setImage:[UIImage imageNamed:@"backArrow"] forState:UIControlStateNormal];
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
//    [button setTitle:@" 返回" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    button.bounds = CGRectMake(0, 0, 70, 30);
    button.contentEdgeInsets = UIEdgeInsetsMake(0, -5, 0, 0);
    button.titleLabel.font = [UIFont systemFontOfSize:16];
    [button addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
}

- (void)back
{
    NSArray *viewcontrollers = self.navigationController.viewControllers;
    if (viewcontrollers.count > 1) {
        if ([viewcontrollers objectAtIndex:viewcontrollers.count - 1] == self) {
            //push方式
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
    else{
        //present方式
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

-(void)drawTitleItems{
    if (_titleItemsView) {
         return;
     }
     self.titleItemsView = [[UIView alloc]initWithFrame:CGRectMake(0, 0,
                                                                    CGRectGetWidth(self.view.frame), 100)];
     _titleItemsView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0];
     
     [self.view addSubview:_titleItemsView];
    self.headerLabel = [LKBaseLabel labelWithFrame:CGRectZero text:[NSString stringWithFormat:@"￥%@",self.price] textColor:[UIColor whiteColor] font:[UIFont fontWithName:@"PingFangSC-Regular" size:36] textAlignment:NSTextAlignmentCenter];
     [_titleItemsView addSubview:self.headerLabel];
     [self.headerLabel mas_makeConstraints:^(MASConstraintMaker *make) {
         make.center.equalTo(self.titleItemsView);
     }];
}


- (void)drawBottomItemsWithTitle:(NSString *)title
{
    if (_bottomItemsView) {        
        return;
    }
    self.bottomItemsView = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.view.frame)-264,
                                                                   CGRectGetWidth(self.view.frame), 200)];
    _bottomItemsView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0];
    
    [self.view addSubview:_bottomItemsView];
    
    LKBaseLabel *introLabel = [LKBaseLabel labelWithFrame:CGRectZero text:title textColor:[UIColor whiteColor] font:[UIFont fontWithName:@"PingFangSC-Regular" size:15] textAlignment:NSTextAlignmentCenter];
     [_bottomItemsView addSubview:introLabel];
     [introLabel mas_makeConstraints:^(MASConstraintMaker *make) {
         make.top.equalTo(self.bottomItemsView);
         make.centerX.equalTo(self.bottomItemsView);
     }];
    
    CGSize size = CGSizeMake(100,140);
    self.btnFlash = [[UIButton alloc] init];
    _btnFlash.bounds = CGRectMake(0, 0, size.width, size.height);
    _btnFlash.center = CGPointMake(CGRectGetWidth(_bottomItemsView.frame)/2, CGRectGetHeight(_bottomItemsView.frame)/2 + 20);
    [_btnFlash setTitle:@"二维码收款" forState:UIControlStateNormal];
    [_btnFlash setImage:[UIImage imageNamed:@"ic_qr_pay"] forState:UIControlStateNormal];
    [_btnFlash addTarget:self action:@selector(openOrCloseFlash) forControlEvents:UIControlEventTouchUpInside];
    [_bottomItemsView addSubview:_btnFlash];
    [_btnFlash mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(introLabel.mas_bottom).offset(20);
        make.centerX.equalTo(self.bottomItemsView);
        make.size.mas_equalTo(CGSizeMake(100, 140));
    }];
    [_btnFlash layoutButtonWithImageStyle:ZJButtonImageStyleTop imageTitleToSpace:10];
    

}
/**
 开启或者关闭闪光灯
 */
-(void)openOrCloseFlash{
    LKCodeCashierViewController *vc = [[LKCodeCashierViewController alloc] init];
    vc.url = self.url;
    vc.order_sn = self.order_sn;
    vc.price = self.price;
    vc.jmt_remark = self.jmt_remark;
    [self.navigationController pushViewController:vc animated:YES];
    return;
    [super openOrCloseFlash];
    if (self.isOpenFlash)
    {
        [_btnFlash setImage:[UIImage imageNamed:@"qrcode_scan_btn_flash_down"] forState:UIControlStateNormal];
    }else{
        [_btnFlash setImage:[UIImage imageNamed:@"qrcode_scan_btn_flash_nor"] forState:UIControlStateNormal];
    }
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark -实现类继承该方法，作出对应处理

- (void)scanResultWithArray:(NSArray<LBXScanResult*>*)array
{
    if (!array ||  array.count < 1)
    {
        [self popAlertMsgWithScanResult:nil];
        
        return;
    }
    
    //经测试，可以ZXing同时识别2个二维码，不能同时识别二维码和条形码
    //    for (LBXScanResult *result in array) {
    //
    //        NSLog(@"scanResult:%@",result.strScanned);
    //    }
    
    LBXScanResult *scanResult = array[0];
    
    NSString*strResult = scanResult.strScanned;
    
    self.scanImage = scanResult.imgScanned;
    
    if (!strResult) {
        
        [self popAlertMsgWithScanResult:nil];
        
        return;
    }
    
    //TODO: 这里可以根据需要自行添加震动或播放声音提示相关代码
    //...
    //震动提醒
//    [LBXScanWrapper systemVibrate];
//    //声音提醒
//    [LBXScanWrapper systemSound];
    [self showNextVCWithScanResult:scanResult];
}

- (void)popAlertMsgWithScanResult:(NSString*)strResult
{
    if (!strResult) {
        
        strResult = @"识别失败";
    }
    
    __weak __typeof(self) weakSelf = self;
    [LBXAlertAction showAlertWithTitle:@"扫码内容" msg:strResult buttonsStatement:@[@"知道了"] chooseBlock:^(NSInteger buttonIdx) {
        
        [weakSelf reStartDevice];
    }];
}
//扫描结果展示
- (void)showNextVCWithScanResult:(LBXScanResult*)strResult {
    NSLog(@"二维码为：%@",strResult.strScanned);
    
    WS(weakSelf)
    NSMutableDictionary *param;
    NSString *url;
    if (self.scanType == LKScanTypeCashier) {
        param = [[NSMutableDictionary alloc] initWithDictionary:@{@"code":strResult.strScanned,@"order_sn":self.order_sn,@"checker":@"0",@"price":self.price,@"jmt_remark":self.jmt_remark}];
        NSString *sign = [NSString encoingWithDic:param];
        [param setObject:sign forKey:@"sign"];
        url = MyPayScanUrl;
        [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:url header:[LKUserInforTool account].token parameters:param progress:^(NSProgress * _Nullable progress) {

        } success:^(BOOL isSuccess, id  _Nullable responseObject) {
            if ([responseObject[@"code"] isEqualToString:@"success"]) {
                NSDictionary * dataDic = responseObject[@"data"][@"data"];
                LKBillListModel *model = [LKBillListModel modelWithDictionary:dataDic];
                LKBillDetailViewController *vc = [[LKBillDetailViewController alloc] init];
                vc.model = model;
                [weakSelf.navigationController pushViewController:vc animated:YES];
            }else{
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:responseObject[@"msg"] preferredStyle:UIAlertControllerStyleAlert];
                  [alert addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                      [weakSelf reStartDevice];
                  }]];
                dispatch_async(dispatch_get_main_queue(), ^{
                      [self presentViewController:alert animated:YES completion:nil];
                });
            }
        } failure:^(NSString * _Nullable errorMessage) {

        }];
    }else if(self.scanType == LKScanTypeScan){

    }else if(self.scanType == LKScanTypeScanTicket){
        
    }else if (self.scanType == LKScanTypeHardware){
        if (self.shopTreasureBlock) {
            self.shopTreasureBlock(strResult.strScanned);
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }
    }else if(self.scanType == LKScanTypeScanTaiqian){
        param = [[NSMutableDictionary alloc] initWithDictionary:@{@"cate_id":[[strResult.strScanned componentsSeparatedByString:@"/"] lastObject]}];
        NSString *sign = [NSString encoingWithDic:param];
        [param setObject:sign forKey:@"sign"];
        url = MyScanTaiqianCodeAddUrl;
        [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:url header:[LKUserInforTool account].token parameters:param progress:^(NSProgress * _Nullable progress) {

        } success:^(BOOL isSuccess, id  _Nullable responseObject) {
            if ([responseObject[@"code"] isEqualToString:@"success"]) {
                NSDictionary * dataDic = responseObject[@"data"];
                LKTaiQianScanBindController *vc = [[LKTaiQianScanBindController alloc] init];
                vc.no_number = dataDic[@"no_number"];
                vc.Id = dataDic[@"id"];
                vc.status = dataDic[@"status"];
                [weakSelf.navigationController pushViewController:vc animated:YES];
            }else{
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:responseObject[@"msg"] preferredStyle:UIAlertControllerStyleAlert];
                  [alert addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                      [weakSelf reStartDevice];
                  }]];
                dispatch_async(dispatch_get_main_queue(), ^{
                      [self presentViewController:alert animated:YES completion:nil];
                });
            }
        } failure:^(NSString * _Nullable errorMessage) {

        }];
    }


}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
